﻿using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PropertyManagementSystemAPI.Authod;
using PropertyManagementSystemAPI.Models;


namespace PropertyManagementSystemAPI.Controllers
{
    /// <summary>
    /// 登录/注册
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [ApiExplorerSettings(GroupName = "登录注册")]
    public class LoginController : ControllerBase
    {
        //通过依赖注入添加
        static IAuthenticateService authService;
        public readonly IFreeSql db;
        public readonly IHttpContextAccessor _httpContextAccessor;
        public LoginController(IAuthenticateService _authService, IFreeSql _db)
        {

            authService = _authService;
            db = _db;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Login([FromQuery] string username, [FromQuery] string password)
        {

            Userinfo u = db.Select<Userinfo>().Where(a => a.UserName == username && a.UserPassword == password).First();
            if (u != null)
            {
                //成功
                string token;
                if (authService.IsAuthenticated(u, out token))
                {
                 HttpContext.Session.SetString("user", u.UserId.ToString());
                    return Ok(token);
                }
                else
                {
                    return Ok(1);
                }

            }
            else
            {
                return Ok(0);
            }
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="ww"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult zhuce(Userinfo ww)
        {
            //注册信息
            var m = db.Insert(ww).ExecuteAffrows();
            return Ok(m);
        }
    }
}
